// @flow
import React, { Component, Fragment, type Node } from 'react';

import './TreeNode.scss';

type Props = {
  datas: Array<any>,
  openedIds: Array<string>,
  openedRange: { level: number, openStatus: 'open' | 'close' },
  treeType: string,
  NodeRender(item: any, isLeaf: boolean, isOpen: boolean): Node,
};

class TreeNode extends Component<Props> {
  // constructor(props: Props) {
  //     super(props);
  // }
  arrFilter = (level: number = 0, pid: string = '') => {
    return this.props.datas.filter((i) => {
      return i.level === level && i.pid === pid;
    });
  };
  isOpen = (item: any) => {
    const { openedIds, openedRange } = this.props;
    // console.log(`openedIds.index:${openedIds.indexOf(item.id)}`);
    // console.log(openedRange);
    return openedIds.indexOf(item.id) !== -1;
    /* ||
      (openedRange.level === -1 && openedRange.openStatus === 'open') ||
      (openedRange.level !== -1 &&
        openedRange.level >= item.level &&
        openedRange.openStatus === 'open') */
  };
  itemRender = (level: number = 0, pid: string = '') => {
    const items = this.arrFilter(level, pid);

    const nodeItems = items.map((item) => {
      const childrenItem = this.arrFilter(level + 1, item.id);
      return (
        <div className="tree-items" treeType={this.props.treeType} key={item.id}>
          <div className="tree-item">
            {this.props.NodeRender(item, childrenItem.length === 0, this.isOpen(item))}
          </div>
          {childrenItem.length > 0 && this.isOpen(item)
            ? this.itemRender(level + 1, item.id)
            : null}
        </div>
      );
    });
    return <ul className="tree-node">{nodeItems}</ul>;
  };
  render() {
    return <Fragment>{this.itemRender()}</Fragment>;
  }
}

export default TreeNode;
